import {Modal, Form, Input, Select, Upload, Button, message} from 'antd';
import {UploadOutlined} from '@ant-design/icons';
import {useState} from "react";

const {Option} = Select;

interface AddModalProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: API.Carousel) => void;
  initialValues?: API.Carousel;
}

export default ({visible, onCancel, onSubmit, initialValues}: AddModalProps) => {
  const [form] = Form.useForm();
  const [fileId, setFileId] = useState<number>(initialValues?.fileId || null)

  return (
    <Modal
      title={initialValues ? '编辑轮播图' : '添加轮播图'}
      visible={visible}
      onCancel={() => {
        form.resetFields();
        onCancel();
      }}
      onOk={() => {
        form.validateFields().then(values => {
          form.resetFields();
          onSubmit({
            ...initialValues,
            ...values,
            fileId: fileId
          } as any);
        });
      }}
      afterOpenChange={async (open) => {
        form.resetFields();
        setFileId(null)
      }}
    >
      <Form form={form} layout="vertical" initialValues={initialValues}>
        <Form.Item
          name="title"
          label="标题"
          rules={[{required: true, message: '请输入标题'}]}
        >
          <Input/>
        </Form.Item>

        <Form.Item name="linkUrl" label="跳转链接">
          <Input placeholder="http://"/>
        </Form.Item>

        <Form.Item
          name="sortOrder"
          label="排序"
          rules={[{required: true, message: '请输入排序值'}]}
        >
          <Input type="number"/>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{required: true, message: '请选择状态'}]}
        >
          <Select>
            <Option value="0">正常</Option>
            <Option value="1">停用</Option>
          </Select>
        </Form.Item>

        <Form.Item label="图片上传">
          <Upload
            listType="picture"
            maxCount={1}
            onChange={(info) => {
              setFileId(info?.file?.response?.data?.id || '')
            }}
            action={'/api/file/upload'}
          >
            <Button icon={<UploadOutlined/>}>选择图片</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};
